<template>
  <div>
      <Breadcard name1="商品管理" name2="商品分类"/>
      <el-card>
          <el-row>
              <el-button type="primary" @click="showCateDialog"> 添加分类</el-button>
          </el-row>
          <tree-table class="tree" :data="cateList" :columns="columns" :selection-type="false" show-index :expand-type="false" border :show-row-hover="false">
              <template slot="isok" slot-scope="scope">
                  <i v-if="scope.row.cat_deleted === false" class="el-icon-success" style="color:lightgreen"></i>
                  <i v-else class="el-icon-error" style="color:red"></i>
              </template>
              <template slot="order" slot-scope="scope">
                  <el-tag v-if="scope.row.cat_level === 0" size="mini" >一级</el-tag>
                  <el-tag v-else-if="scope.row.cat_level === 1" size="mini" type="success" >二级</el-tag>
                  <el-tag v-else size="mini" type="warning">三级</el-tag>
              </template>
              <template slot="opt" slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="showeditDialog(scope.row)">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeCate(scope.row.cat_id)">删除</el-button>
              </template>
          </tree-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryinfo.pagenum"
            :page-sizes="[1,2,5,10]"
            :page-size="queryinfo.pagesize"
            layout="total,sizes, prev, pager, next,jumper"
            :total="total">
          </el-pagination>
      </el-card>
      <!--添加分类对话框-->
      <el-dialog
        title="添加分类"
        @close="clearCateDialog"
        :visible.sync="cateDialogVisible"
        width="50%">
        <el-form :model="addCateForm" status-icon label-width="100px" ref="addCateformRef">
            <el-form-item label="分类名称：" prop="cat_name">
                <el-input v-model="addCateForm.cat_name"></el-input>
            </el-form-item>
            <el-form-item label="父级分类：">
                <!--options用来指定数据源-->
                <!--props用来指定配置对象-->
                <el-cascader
                    :props="{ expandTrigger: 'hover',...cascaderProps ,checkStrictly:true}"
                    v-model="selectedKeys"
                    :options="parentCateList"
                    @change="parentCateChange" 
                    clearable>
                </el-cascader>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cateDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="修改商品分类"
        :visible.sync="editDialogVisible"
        width="50%">
        <el-form :model="editForm" status-icon :rules="editFormrules" ref="editFormRef" label-width="100px">
            <el-form-item label="分类名称" prop="cat_name">
                <el-input type="primary" v-model="editForm.cat_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editCateInfo">确 定</el-button>
        </span>
      </el-dialog>


  </div>
</template>

<script>
import Breadcard from '../../components/Breadcard/Breadcard.vue'
export default {
    components:{
        Breadcard
    },
    data () {
        return {
            queryinfo:{
                pagenum:1,
                pagesize:5
            },
            cateList:[],
            total:0,
            columns:[
                {
                    label:'分类名称',
                    prop:'cat_name'
                },
                {
                    label:'是否有效',
                    //表示将当前定义为模板列
                    type:'template',
                    //表示当前这一列使用模板的名称
                    template:'isok',
                },
                {
                    label:'排序',
                    type:'template',
                    template:'order'
                },
                {
                    label:'操作',
                    type:'template',
                    template:'opt'
                }
            ],
            //控制添加分类对话框显隐
            cateDialogVisible:false,
            //要添加分类的信息
            addCateForm:{
                cat_name:'',
                cat_pid:0,
                cat_level:0
            },
            //父级分类列表
            parentCateList:[],
            //选中的父级分类的id数组
            selectedKeys:[],
            //指定级联选择器的配置对象
            cascaderProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            //控制编辑对话框显隐
            editDialogVisible:false,
            //存放当前查询的分类的id
            editCateId:'',
            //存放查询到的分类信息
            editForm:[],
            //编辑表单检验规则
            editFormrules:{
                cat_name:[
                    {required:true,message:'请输入商品分类名称',trigger:'blur'}
                ]
            }
        }
    },
    created(){
        this.getCateList()
    },
    methods:{
        async getCateList(){
            const {data:res} = await this.$http.get('categories',{
                params:this.queryinfo
            })
            if(res.meta.status !== 200){
                return this.$message.error('获取商品分类失败')
            }
            this.cateList = res.data.result
            this.total = res.data.total
        },
        handleSizeChange(newPage){
            this.queryinfo.pagesize = newPage
            this.getCateList()
        },
        handleCurrentChange(newPage){
            this.queryinfo.pagenum = newPage
            this.getCateList()
        },
        showCateDialog(){
            //先获取父级分类的数据
            this.getParentCateList()
            this.cateDialogVisible= true
        },
        //获取父级分类的数据列表
        async getParentCateList(){
            const {data:res} = await this.$http.get('categories',{
                params:{type:2}
            })
            if(res.meta.status !== 200){
                return this.$message.error('获取父级分类失败')
            }
            this.parentCateList = res.data

        },
        parentCateChange(){
            console.log(this.selectedKeys)
            //当selectedKeys的长度大于零食表示有选中的父级分类，并且所添加的分类的等级与该数组的长度事项等的，
            //父级分类的id总是与该数组的最后一位的id相同
            if(this.selectedKeys.length > 0){
                this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length-1]
                this.addCateForm.cat_level = this.selectedKeys.length
            }else{
                this.addCateForm.cat_pid = 0
                this.addCateForm.cat_level = 0
            }
        },
        async addCate(){
            console.log(this.addCateForm)
            const {data:res}  = await this.$http.post('categories',this.addCateForm)
                if(res.meta.status !== 201){
                    return this.$message.error('添加分类失败')
                }
                this.$message.success('添加分类成功')
                this.getCateList()
                this.cateDialogVisible = false
        },
        clearCateDialog(){
            this.$refs.addCateformRef = '',
            this.selectedKeys = [],
            this.addCateForm.cat_level = 0,
            this.addCateForm.cat_pid = 0
        },
        //编辑按钮
        async showeditDialog(cateInfo){
            this.editCateId = cateInfo.cat_id
            const {data:res} = await this.$http.get('categories/' + cateInfo.cat_id)
            //console.log(res.data)
            if(res.meta.status !== 200){
                return this.$message.error('查询分类失败')
            }
            this.$message.success('查询分类成功')
            this.editForm = res.data
            this.editDialogVisible = true
        },
        async editCateInfo(){
            const {data:res} = await this.$http.put('categories/' + this.editForm.cat_id,{cat_name:this.editForm.cat_name})
            if(res.meta.status !== 200){
                return this.$message.error('修改商品分类失败')
            }
            this.getCateList()
            this.editDialogVisible = false
        },
        // 删除分类
    async removeCate(cat_id) {
      const confirRustle = await this.$confirm('此操作将永久删除该文件, 是否继续?', '删除分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirRustle !== 'confirm') {
        return this.$message.info('已取消删除操作!')
      }

      const { data: res } = await this.$http.delete('categories/' + cat_id)
      if (res.meta.status !== 200) {
        return this.$message.error('分类删除失败!')
      }
      this.$message.success('该分类已经成功删除!')
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>
.tree{
    margin-top: 15px;
}
.el-card{
    margin-top: 15px;
}
</style>